<template>
	<view class="container">
		<radio-group @change="fixedRadioChange" class="box" v-if="JSON.stringify(mapData.appointInfo) != '{}' && mapData.appointInfo.user">
			<label>
				<view class="list_content">
					<view class="content_box">
						<view class="studio_img">
							<image :src="mapData.appointInfo.user.avatar" mode=""></image>
							<!-- <view class="storeManage" v-if="identity == 1">店长</view> -->
						</view>
						<view class="studio_text">
							<view class="studio_text_name">
								<view class="studio_text_name_title">
									<view>{{mapData.appointInfo.user.nickName}}</view>
									<view class="appoint">指定陪宠师</view>
								</view>
								<radio value="r1" :checked="mapData.fixedChecked" color="#F85959" />
							</view>
							<view class="studio_text_tips">
								<text class="option">{{mapData.appointInfo.user.realName}}</text>
								<text class="option">{{mapData.appointInfo.user.sex == 0 ? '女' : '男'}}</text>
								<text class="option">{{mapData.appointInfo.user.age}}岁</text>
								<text class="option">{{mapData.appointInfo.user.phone}}</text>
							</view>
							<view class="studio_text_address">
								<text>距服务地址{{ parseInt(mapData.appointInfo.distance) || 0 }}M |</text>
								{{mapData.appointInfo.user.province}}{{mapData.appointInfo.user.city}}{{mapData.appointInfo.user.area}}{{mapData.appointInfo.user.locationAddress}}{{mapData.appointInfo.user.address}}
							</view>
							<view class="serveDistance">服务范围：{{mapData.appointInfo.user.orderTakingRange}}KM</view>
						</view>
					</view>
				</view>
			</label>
		</radio-group>
		
		<view class="studio_list" :class="{noFixedHeight:JSON.stringify(mapData.appointInfo) == '{}'}"  v-if="mapData.list && mapData.list.length > 0">
			<scroll-view :scroll-y="true" class="area-scroll" @scrolltolower="lower">
				<view class="list_content">
					<radio-group @change="radioChange">
						<label v-for="(studioItem,studioIndex) in mapData.list" :key="studioIndex">
							<template v-if="studioItem.user">
								<view class="content_box" >
									<view class="studio_img">
										<image :src="studioItem.user.avatar" mode=""></image>
									</view>
									<view class="studio_text">
										<view class="studio_text_name">
											<view class="studio_text_name_title">
												<view class="title">{{studioItem.user.nickName}}</view>
												<!-- <view class="appoint">指定陪宠师</view> -->
											</view>
											<radio :value="studioItem.userId" :checked="studioIndex === mapData.current" color="#F85959" />
										</view>
										<view class="studio_text_tips">
											<text class="option" v-if="studioItem.user.realName && studioItem.user.realName !=''">{{studioItem.user.realName}}</text>
											<text class="option">{{studioItem.user.sex == 0 ? '女' : '男'}}</text>
											<text class="option" v-if="studioItem.user.age >= 0">{{studioItem.user.age}}岁</text>
											<text class="option">{{studioItem.user.phone}}</text>
										</view>
										<view class="studio_text_address">
											<text v-if="studioItem.distance">距服务地址{{ parseInt(studioItem.distance) || 0 }}M |</text>
											{{studioItem.user.province}}{{studioItem.user.city}}{{studioItem.user.area}}{{studioItem.user.locationAddress}}{{studioItem.user.address}}
										</view>
										<view class="serveDistance">服务范围：{{studioItem.user.orderTakingRange}}KM</view>
									</view>
								</view>
							</template>
						</label>
					</radio-group>
				</view>
				<uni-load-more iconType="auto" :status="mapData.loading" />
			</scroll-view>
		</view>
		<view class="empty_box" v-if="!mapData.appointInfo && mapData.list.length <= 0">
		  <image class="empty_img" src="https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/icon-54.png"></image>
		  <view>暂无数据~</view>
		</view>
		<view class="area-btn" v-if="mapData.appointInfo || mapData.list.length > 0">
			<view class="area-btn_box" @click="submit">确定</view>
		</view>
		
		<uni-popup ref="popupRef" type="center" :is-mask-click="false">
			<view class="unbind_pop">
				<view class="pop_title">确定派给该陪宠师吗？</view>
				<view class="unbind_text linehei1" v-if="mapData.tipsTextShow">注意：此陪宠师不是用户的指定陪宠师。</view>
				<view class="pop_footer_btn">
					<view class="cancel_btn" @click="btnCancel()">取消</view>
					<view @click="handleConfig" class="xjs-btn-primary confirm_btn">确认</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script lang="ts" setup>
	import { ref, reactive, onMounted } from 'vue'
	import api from '@/api'
	import { onLoad ,onPullDownRefresh, onReachBottom} from '@dcloudio/uni-app'
	import {useStudioStoreToRefs} from "@/store/useStudioStore";
	const url = 'https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/'  //图片前缀
	let {identity, studio} = useStudioStoreToRefs()
	const petsitterUserId = ref('')
	const petsitterItem = ref({})
	const popupRef = ref()
	const mapData = reactive<{
		loading : string
		page : number
		limit : number
		current:number
		list: any
		appointInfo:any
		fixedChecked:boolean
		paramsData:any
		tipsTextShow:boolean
	}>({
		loading: 'more',
		page: 1,
		limit: 20,
		current:-1,
		fixedChecked:true,
		appointInfo:{},
		paramsData:{},
		list: [],
		tipsTextShow:false
	})
	
	onLoad((params) =>{
		mapData.paramsData = params
	})
	
	onMounted(async () => {
	  await getAppointInfo()
	  await getList()
	  scrollToTop()
	  setTimeout(() => {
	  	if(JSON.stringify(mapData.appointInfo) == '{}'){
	  		mapData.current = 0
	  		petsitterUserId.value= mapData.list[0].userId
	  	}
	  })
	})
	
	const btnCancel = () => {
		popupRef.value.close()
	}
	
	// 判断订单状态变更
	const handleOrderStatusChange = async () => {
	  return new Promise(async (resolve, reject) => {
	    const res = await api({
	      method: 'get',
	      url: `/mall/order/checkOrderStatus?orderId=${mapData.paramsData.id}&status=${mapData.paramsData.status}&type=-1`,
	    })
	    if (res.code == 0) {
	      if (res.data == 1) {
	        uni.showModal({
	          title: '提示',
	          content: '数据已过期，请刷新重试',
	          showCancel: false,
	          confirmText: '返回派单',
	          success: (res) => {
	            if (res.confirm) {
	              // onDataInit()
				  uni.navigateBack({ delta: -1 })
	            }
	          }
	        })
	        reject(false)
	      } else {
	        resolve(true)
	      }
	    } else {
	      reject(false)
	    }
	  })
	}
	
	const submit = async() => {
		if(JSON.stringify(mapData.appointInfo) == '{}' && (!petsitterUserId.value || petsitterUserId.value == '')){
			uni.showToast({
				icon: 'none',
				mask: true,
				title: '请选择派单对象'
			})
			return false
		}
		await handleOrderStatusChange()
		mapData.tipsTextShow = JSON.stringify(mapData.appointInfo) != '{}' && !mapData.fixedChecked ?true:false
		popupRef.value.open()
		// uni.showModal({
		//   title: '确定派给该陪宠师吗？',
		//   content: `${JSON.stringify(mapData.appointInfo) != '{}' && !mapData.fixedChecked ? '注意：此陪宠师不是用户的指定陪宠师' : ''}`,
		//   success: async (result) => {
		// 	  if (result.confirm){
		// 		const res = await api({
		// 		  method: 'post',
		// 		  url: `/mall/order/dispatchOrder`,
		// 		  data:{
		// 			  studioId: studio.value.id,
		// 			  id: mapData.paramsData.id,
		// 			  petsitterUserId:JSON.stringify(mapData.appointInfo) != '{}' && mapData.fixedChecked ? mapData.appointInfo.userId : petsitterUserId.value
		// 		  }
		// 		})
		// 		if (res.code !== 0) {
		// 			uni.showToast({
		// 				icon: 'none',
		// 				mask: true,
		// 				title: res.msg
		// 			})
		// 			return false
		// 		}else{
		// 			uni.showToast({
		// 				icon: 'none',
		// 				mask: true,
		// 				title: '修改成功'
		// 			})
		// 			uni.navigateTo({
		// 			  url: `/pages/myStudio/studio/dispatchSuccess/index?type=dispatch&serviceDays=${mapData.paramsData.serviceDays}`,
		// 			})
		// 		} 
		// 	  } 
		//   }
		// })
	}
	
	const handleConfig = async() => {
		const res = await api({
			  method: 'post',
			  url: `/mall/order/dispatchOrder`,
			  data:{
				  studioId: studio.value.id,
				  id: mapData.paramsData.id,
				  petsitterUserId:JSON.stringify(mapData.appointInfo) != '{}' && mapData.fixedChecked ? mapData.appointInfo.userId : petsitterUserId.value
			  }
		})
		if (res.code !== 0) {
			uni.showToast({
				icon: 'none',
				mask: true,
				title: res.msg
			})
			return false
		}else{
			uni.showToast({
				icon: 'none',
				mask: true,
				title: '操作成功'
			})
			btnCancel()
			uni.navigateTo({
			  url: `/pages/myStudio/studio/dispatchSuccess/index?type=dispatch&serviceDays=${mapData.paramsData.serviceDays}`,
			})
		} 
	}
	
	// 获取指定人员信息
	const getAppointInfo = async () => {
	  const res = await api({
	    method: 'get',
	    url: `/mall/studio/petsitter-team/dispatchUserDetail?orderId=${mapData.paramsData.id}`
	  })
	  console.log(res,'45454')
	  mapData.appointInfo = res.data || {}
	}
	
	const fixedRadioChange = (evt) => {
		mapData.fixedChecked = true
		mapData.current = -1
	}
	
	const radioChange = (evt) => {
		mapData.fixedChecked = false
		for (let i = 0; i < mapData.list.length; i++) {
			if (mapData.list[i].userId == evt.detail.value) {
				mapData.current = i;
				petsitterUserId.value = mapData.list[i].userId
				petsitterItem.value = mapData.list[i]
				break;
			}
		}
	}
	
	const getList = async () => {
		uni.showLoading({
			title: '加载中',
			mask: true
		})
		mapData.loading = 'loading'
		const { data: { total = 0, records = [] } } : any = await api({
			method: 'get',
			url: `/mall/studio/petsitter-team/dispatchPage`,
			data: {
				page: mapData.page,
				limit: mapData.limit,
				orderId: mapData.paramsData.id
			}
		})
		if (records) {
			mapData.list = mapData.page == 1 ? records : mapData.list.concat(records)
			if (!records.length || mapData.list.length >= total) {
				mapData.loading = 'noMore'
			} else {
				mapData.loading = 'more'
			}
			console.log(mapData.list, 'mapData.addressList')
		} else {
			mapData.loading = 'more'
		}
		uni.hideLoading()
	}
	
	const onDataInit = async () => {
		mapData.page = 1
	}
	const scrollToTop = () => {
		uni.pageScrollTo({
			scrollTop: 0,
			duration: 300
		})
	}
	
	// 页面下拉刷新
	onPullDownRefresh(async () => {
		console.log('onPullDownRefresh');
		if (mapData.loading == 'loading') {
			uni.stopPullDownRefresh()
		} else {
			try {
				await onDataInit()
				await getList()
			} catch (error) {
			}
			uni.stopPullDownRefresh()
		}
	})
	// 触底
	onReachBottom(async () => {
		console.log('onReachBottom');
		if (mapData.loading == 'noMore') return false
		mapData.page++
		await getList()
		
	})
	
	const lower = () => {
	}
</script>

<style lang="scss" scoped>
	.unbind_pop {
			width: 622rpx;
			background: #FFFFFF;
			border-radius: 24rpx;
			padding: 64rpx 40rpx;
			box-sizing: border-box;
			text-align: center;
		
			.pop_title {
				font-weight: 500;
				font-size: 40rpx;
				color: #1B2120;
		
			}
		
			.unbind_text {
				margin-top: 48rpx;
				font-size: 30rpx;
				color: #1B2120;
			}
			.pop_footer_btn {
				display: flex;
				justify-content: space-between;
				margin-top: 48rpx;
		
				.cancel_btn {
					display: flex;
					justify-content: center;
					align-items: center;
					width: 263rpx;
					height: 88rpx;
					background-color: #FFFFFF;
					border-radius: 44rpx;
					border: 2rpx solid #FF6084;
					font-weight: 400;
					font-size: 28rpx;
					color: #FF6084;
		
				}
		
				.confirm_btn {
					width: 263rpx;
					height: 88rpx;
				}
			}
	}
	.empty_box {
	  text-align: center;
	  font-weight: 400;
	  font-size: 32rpx;
	  color: #1B2120;
	
	  .empty_img {
	    width: 400rpx;
	    height: 315rpx;
	    margin-top: 320rpx;
	    margin-bottom: 50rpx;
	  }
	}
	.noFixedHeight{
		height: calc(100vh - 108rpx) !important;
	}
	.studio_list {
		height: calc(100vh - 260rpx - 108rpx);
		//#ifdef H5
		height: calc(100vh - 598rpx);
		//#endif
		
		// padding: 0 0 calc(constant(safe-area-inset-bottom) + 10rpx);
		// padding: 0 0 calc(env(safe-area-inset-bottom) + 10rpx);
		box-sizing: border-box;
		.area-scroll {
			// height: calc(100%);
			// padding: 0 32rpx;
			// box-sizing: border-box;
			padding: 0 0 calc(constant(safe-area-inset-bottom) + 108rpx);
			padding: 0 0 calc(env(safe-area-inset-bottom) + 108rpx);
		}
	}
	.box{
		position: sticky;
		top: 0;
		width: 100%;
		z-index: 1;
	}
	.list_content {
		.content_box {
			width: 686rpx;
			margin: 0 auto;
			margin-top: 24rpx;
			padding: 32rpx 24rpx;
			box-sizing: border-box;
			background-color: #fff;
			display: flex;
			justify-content: space-between;
			border-radius: 24rpx;
			.studio_img {
				position: relative;
				width: 136rpx;
				height: 136rpx;
				.storeManage{
					position: absolute;
					bottom: 0;
					left: 50%;
					transform: translateX(-50%);
					width: 96rpx;
					line-height: 40rpx;
					background: linear-gradient( 90deg, #FFA6BC 0%, #FFA3A3 100%);
					border-radius: 40rpx;
					text-align: center;
					color: #fff;
					font-size: 24rpx;
				}
				image {
					width: 136rpx;
					height: 136rpx;
					border-radius: 50%;
				}
			}
	
			.studio_text {
				// width: 444rpx;
				margin-left: 16rpx;
				width: calc(100% - 136rpx - 16rpx);
				.option{
					position: relative;
					margin-right: 40rpx;
					&:last-child{
						margin-right: 0;
						&::after{
							content: none;
						}
					}
					&::after{
						content: '';
						position: absolute;
						right: -20rpx;
						transform: translateY(-50%);
						top: 50%;
						height: 26rpx;
						width: 1rpx;
						background-color: #7C807F;
					}
				}
				.studio_text_name {
					margin-bottom: 30rpx;
					font-size: 36rpx;
					color: #1B2120;
					font-weight: bold;
					line-height: 1;
					display: flex;
					align-items: center;
					justify-content: space-between;
					.studio_text_name_title{
						display: flex;
						align-items: center;
						.title{
							max-width: 350rpx;
							overflow: hidden;
							text-overflow: ellipsis;
							white-space: nowrap;
						}
					}
					image{
						width: 48rpx;
						height: 48rpx;
						border-radius: 50%;
					}
					.appoint{
						width: 136rpx;
						line-height: 40rpx;
						text-align: center;
						background: linear-gradient( 90deg, #FFA6BC 0%, #FFA3A3 100%);
						border-radius: 24rpx 24rpx 24rpx 0px;
						font-size: 24rpx;
						color: #fff;
						margin-left: 8rpx;
					}
				}
	
				.studio_text_tips {
					margin-bottom: 26rpx;
					font-size: 24rpx;
					color: #5C5E5E;
					line-height: 1.2;
				}
	
				.studio_text_address {
					font-size: 24rpx;
					line-height: 40rpx;
					color: #7C807F;
					.studio_text_address_km {
						color: #5C5E5E;
						font-weight: bold;
					}
	
					.studio_text_address_splice {
						margin: 0 8rpx;
						display: inline-block;
						width: 2rpx;
						height: 20rpx;
						background-color: #7C807F;
					}
	
					.studio_text_address_detail {
	
						color: #7C807F;
					}
				}
				.serveDistance{
					font-size: 24rpx;
					color: #5C5E5E;
					margin-bottom: 16rpx;
				}
			}
		}
	}
	.area-btn {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		background-color: #fff;
		padding-bottom: calc(var(--safe-area-bottom));
		line-height: 1;
		.area-btn_box {
			width: 686rpx;
			margin: 8rpx auto;
			padding: 30rpx;
			background: linear-gradient( 90deg, #FF6188 0%, #FF5252 100%);
			font-size: 28rpx;
			color: #FFFFFF;
			border-radius: 62rpx;
			text-align: center;
		}
	}
</style>